package com.tywj.lib.core.common.view

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager

/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/5/8
 *     desc   : fragment切换管理器
 *     version: 1.0.0
 * </pre>
 */
class FragmentChangeManager(
    private val fragmentManager: FragmentManager,
    private val containerViewId: Int,
    private val fragments: ArrayList<Fragment>,
    private val tags: ArrayList<String> = ArrayList(),
    /**
     * 第一个可见的Fragment索引，默认是第一个
     */
    private val firstVisibleFragmentIndex: Int = 0
) {

    var currentIndex = 0
        set(value) {
            if (field != value && value in 0 until fragments.size) {
                changeVisibleFragment(value)
                field = value
            }
        }

    val currentFragment
        get() = fragments[currentIndex]

    init {
        initFragments()
    }

    private fun initFragments() {
        when {
            tags.isEmpty() -> {
                for (fragment in fragments) {
                    val ft = fragmentManager.beginTransaction()
                    if (!fragment.isAdded) {
                        ft.add(containerViewId, fragment)
                    }
                    ft.hide(fragment).commitAllowingStateLoss()
                }
            }
            fragments.size != tags.size -> {
                throw IllegalArgumentException("tag size must equal fragment size!")
            }
            else -> {
                fragments.forEachIndexed { index, fragment ->
                    val ft = fragmentManager.beginTransaction()
                    if (!fragment.isAdded) {
                        ft.add(containerViewId, fragment, tags[index])
                    }
                    ft.hide(fragment).commitAllowingStateLoss()
                }
            }
        }

        changeVisibleFragment(firstVisibleFragmentIndex)
    }

    private fun changeVisibleFragment(index: Int) {
        for (i in fragments.indices) {
            val ft = fragmentManager.beginTransaction()
            val fragment = fragments[i]
            if (i == index) {
                ft.show(fragment)
            } else {
                ft.hide(fragment)
            }
            ft.commitAllowingStateLoss()
        }
    }
}